/**
 * 展示折扣dialog
 */
import React,{useImperativeHandle, useState} from 'react';
import { Col, Row,Descriptions, Button, Divider, Steps,Image, Table, Drawer, Upload ,Modal, message, Popconfirm} from 'antd';
import icon0s from '@/assets/imgs/icon0s.png';
import icon0n from '@/assets/imgs/icon0n.png';
import icon1s from '@/assets/imgs/icon1s.png';
import icon1n from '@/assets/imgs/icon1n.png';
import icon2s from '@/assets/imgs/icon2s.png';
import icon2n from '@/assets/imgs/icon2n.png';
import icon3s from '@/assets/imgs/icon3s.png';
import icon3n from '@/assets/imgs/icon3n.png';
import icon4s from '@/assets/imgs/icon4s.png';
import icon4n from '@/assets/imgs/icon4n.png';
import icon5s from '@/assets/imgs/icon5s.png';
import html2canvas from 'html2canvas';
import ProTable from '@ant-design/pro-table';
import { accMul, accSub, exportFile, moneyFormat, moneyFormat2, priceOption } from '@/utils/utils';
import InputDialog from './InputDialog';
import request from '@/utils/request';
import { DrawerForm } from '@ant-design/pro-form';
import { ExclamationCircleOutlined } from '@ant-design/icons';
const { confirm } = Modal;

const { Step } = Steps;

export type Order = {
  approve:boolean,
  admin:false,
  onRefersh?: () => void;
};

const OrderInfo: React.FC<any> = React.forwardRef((props:any,ref:any)=>{
    const [modalVisible, setModalVisible] = useState(false);
    const [attList,setAttList] = useState<any>([]);
    // const [pList,setPList] = useState<any>([]);
    const [order,setOrder] = useState<any>({});
    const [otherData,setOtherData] = useState<any>({});
    const [agreement,setAgreement] = useState<any>({});
    const [inputDialog,setInputDialog] = useState(false);
    const [inputDialog2,setInputDialog2] = useState(false);

    const [spFlag,setSpFlag]= useState(false);
    const [btFlag,setBtFlag] = useState(false);
    const [inputText,setInputText] = useState('');
    const [printFlag,setPrintFlag]= useState(false);
    const [inputFlag,setInputFlag]= useState(false); 
    const [proData,setProData] = useState<any[]>([]);
    const handlePreview = ()=>{
      if(attList.length>0){
        window.open(attList[0].url)
      }else{
        message.warning('暂无合同')
      }
    }

    const columns = [
      {
        title: '序号',
        dataIndex: 'seq',
        width:50,
        renderText: (value: any, record: any, index: number) => {
          return index+1
        }
      }, {
        title: '产品型号',
        // ellipsis: true,
        dataIndex: 'productCode',
        renderText: (value: any, record: any, index: number) => {
          return record.productCode
        }
      },
      {
        title: '产品名称',
        dataIndex: 'productName',
        ellipsis: true,
        renderText: (value: any, record: any, index: number) => {
          return record.productName
        }
      },{
        title: '产品分类',
        dataIndex: 'productType',
        width: 100,
        // valueType:'select',
        // valueEnum:productTypeOption()
       
      }, {
        title: '单位',
        dataIndex: 'sellUnit',
        width: 60,
        ellipsis:true,
        renderText: (value: any, record: any, index: number) => {
          return record.sellUnit
        }
      },
      // {
      //   title: ()=><span>个/包<br/>(可使用次数)</span>,
      //   dataIndex: 'packing_unit',
      //   width: 100,
      //   ellipsis:true,
      //   renderText:()=>'10个/箱'
      // },
      {
        title: '数量',
        dataIndex: 'quantity',
        editable: true,
        width: 60,
      }, 
      // {
      //   title: '合计',
      //   dataIndex: 'numbs_count',
      //   width: 70,
      //   colSpan: 1,
      //   align: 'center',
      //   render: (value: any, record: any) => {
      //     const obj:any = {
      //       children: value,
      //       props: {}
      //     };
      //     obj.props.rowSpan = record.name_count;
      //     return obj;
      //   }
      // }, 
      
      {
        title: '税率',
        width: 60,
        align: 'left',
        dataIndex: 'taxRate',
        renderText: (taxRate:any) => {
          return taxRate+'%';
        }
      },
      {
        title: '单价(元)',
        width: 150,
        align: 'left',
        render: (_: any, record: any) => {
          if (record.actualPrice!=record.originalPrice) {
            return <>{moneyFormat(record.actualPrice)}<span style={{
                textDecoration: 'line-through',
                color: '#d1d1d1',
                marginLeft: 10
              }}>{moneyFormat(record.originalPrice)}</span></>;
          }
          return moneyFormat(record.actualPrice)
        }
      }, 
      // {
      //   title: '折扣率',
      //   width: 90,
      //   key: 'disRate',
      //   align: 'left',
      //   render: (_: any, record: any) => {
      //     return order.discountRate
      //   }
      // },
       {
        title: '金额(元)',
        width: 150,
        key: 'money',
        align: 'left',
        render: (_: any, record: any) => {
          return moneyFormat(accMul(record.actualPrice , record.quantity));
          // return ''
        }
      }
    ];

      useImperativeHandle(ref,()=>({
        init:async(order:any,sfFlag:boolean)=>{
          setOrder({orderNumber:'ORDER20230312101',buyer:'XXXX人民医院',orderTime:'2023-09-01',
          totalActualAmountTaxExcluded:50000,
          totalActualAmount:accMul(50000,1.13)
          ,orderRemark:'订单的备注'})
          setProData([
          {productCode:4002001,
            productName:'手术剪',
            productType:'一次性耗材',
            sellUnit:'个',
            quantity:10,
            taxRate:13,
            actualPrice:50000,
            originalPrice:50000}
          ])
          setModalVisible(true)
        }
      }));
      
    const getStep = ()=>{
      // debugger
      
        return <>
              <Step status="wait" title="待审核" />
              <Step status="wait" title="待付款" />
              <Step status="wait" title="待发货" />
              <Step status="wait" title="待收货"  />
              <Step status="wait" title="已完成" />
          </>
    }

    const getOkText = ()=>{
      return '审批通过'
    }
    const backBtn=(defaultDoms:any)=>{
      return [...defaultDoms, <Button danger key='ok' onClick={async() => {
        setInputFlag(true)
        setInputText('')
        setInputDialog(true)
        setBtFlag(true)
      }}>退回</Button>]
  }

  const uploadProps = {
    name: 'file',
    accept: 'image/*,application/pdf',
    action: '/intufosun/common/upload',
    beforeUpload: (file: any, FileList: any[]) => {
      var flag = file.type.indexOf('image/') >= 0 || file.type.indexOf('pdf') >= 0;
      if (!flag) {
        message.error('请上传图片格式或pdf格式');
      }
      return flag;
    }
  };

  const uploadBtn=(btnText:string)=>{
    return  <Upload {...uploadProps} maxCount={1} fileList={attList} showUploadList={{
      showRemoveIcon: false
    }} onPreview={handlePreview} onChange={async(info: any) => {
      if (info.file.status === 'done') {

        if(attList.length>0){
          await request(`/intufosun/business/attachment/${attList[0].uid}`,{method:'delete'})
        }
        if(sessionStorage.getItem('access')=='dealer'){
          await request(`/intufosun/business/order/orderAttNotice/${order.id}`,{method:'get'})
        }
        if (info.file.response.code == 200) {
          var fileList: any[] = [];
          message.success(`${info.file.name}上传成功`);
          var data = info.file.response;
          data.uid = data.id;
          data.name = info.file.name;
          data.url = data.url;
          data.status = 'done';
          fileList.push(data);
          setAttList(fileList)
        } else {
          message.error(`${info.file.name} 上传失败.`);
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败.`);
      }
    }} data={{
      'shipId': order.shipId,
      'clear': 1
    }} headers={{
      'authorization': `${sessionStorage.getItem('token')}`
    }}>
      <Button id='printBtn5' type='primary' size='small'>{btnText}</Button>
    </Upload>
  }
  

    return (
      <DrawerForm  title={'详情'} width={1300}
      submitter={
     {
       searchConfig: {
         submitText: getOkText(),
         resetText: '取消'
       },
       render: (props, defaultDoms) => {
        if(!spFlag){
          return defaultDoms[0]
        }
        if(sessionStorage.getItem('access')!='dealer'&&(order?.orderOperationFlow?.orderStatus==2||order?.orderOperationFlow?.orderStatus==3||order?.orderOperationFlow?.orderStatus==4||order?.orderOperationFlow?.orderStatus==5)){
          defaultDoms= [<Popconfirm title='确定关闭吗?'     key='close' onConfirm={() => {
            // closeOrder(order.id)
           }}><Button type='dashed'>关闭</Button></Popconfirm>,...defaultDoms]
        }

        if(order?.orderOperationFlow?.orderStatus==2||(order?.isEdited==1&&order?.isFrozen==1)){
          return backBtn(defaultDoms);
        }
        return defaultDoms
       }
     }}
           onVisibleChange={v=>{
             setModalVisible(v)
           }}
           drawerProps={{
             destroyOnClose:true,
             forceRender:true,
           }}
           visible={modalVisible}
           onFinish={async (values: any) => {
            
               return false;
          
           }}>
         <Row >
            <Col span={5} style={{borderRight:'1px solid #f0f0f0'}}>
                <Descriptions title="订单基本信息" column={1} size="small" labelStyle={{width:90,color:'#444444',fontWeight:700}}>
                    <Descriptions.Item  label="订单号">{order.orderNumber}</Descriptions.Item>
                    <Descriptions.Item  label="订单类型">{'普通订单'}</Descriptions.Item>
                    {/* <Descriptions.Item  label="经销商代码">{order.dealerCode}</Descriptions.Item> */}
                    <Descriptions.Item  label="客户名称">{order.buyer}</Descriptions.Item>
                    <Descriptions.Item label="订货日期">{order.orderTime}</Descriptions.Item>
                    {/* <Descriptions.Item label="交货日期">{order.deliveryDate}</Descriptions.Item> */}
                    {/* <Descriptions.Item label="付款方式">{order.payment_method}</Descriptions.Item> */}
                    {/* <Descriptions.Item label="运费方式">{order.postPayMethod}</Descriptions.Item> */}
                    {/* <Descriptions.Item  label="销售">{order.salesName}</Descriptions.Item> */}
                    <Descriptions.Item  label="附件" contentStyle={{color:'#4091f7',cursor:'pointer'}}>

                      {
                        sessionStorage.getItem('access')=='dealer'?
                        attList.length==0?<>
                            {uploadBtn('上传')}
                        </>:<span onClick={()=>{
                          handlePreview()
                        }} style={{paddingRight:20}}>{attList.length>0?attList[0].name:''}</span>
                        :sessionStorage.getItem('access')=='checker'&&(order?.orderOperationFlow?.orderStatus!='1'&&order?.orderOperationFlow?.orderStatus!='7'&&order?.orderOperationFlow?.orderStatus!='8')?
                        uploadBtn('修改'):<>
                        <span onClick={()=>{
                          handlePreview()
                        }} style={{paddingRight:20}}>{attList.length>0?attList[0].name:''}</span></>
                      }
                      
                    
                    </Descriptions.Item>
                    <Descriptions.Item  label="备注">{order.orderRemark?order.orderRemark+'':''}</Descriptions.Item>
                </Descriptions>
                {/* {sessionStorage.getItem('access')=='admin'?<Button onClick={()=>{
                  setInputText(order?.orderRemark)
                  setInputDialog2(true)
                }} type='primary' size='small' key="editBak">修改备注</Button>:<></>} */}
                <Divider />
                <Descriptions title="收货信息" column={1} size="small" labelStyle={{width:90,color:'#444444',fontWeight:700}} contentStyle={{paddingRight:20}}>
                    <Descriptions.Item label="收货人">{'李四'}</Descriptions.Item>
                    <Descriptions.Item label="收货电话">{'19887898621'}</Descriptions.Item>
                    <Descriptions.Item label="收货地址">{'北京市朝阳区XXXX医院'}</Descriptions.Item>
                </Descriptions>
                <Row gutter={[0, 20]} style={{marginTop:20}}>
                  <Col span={12}>
                  <Button id="printBtn1" style={{width:102}}  type="primary" key="export1" onClick={async()=>{
                   

                  }}>
                    excel导出
                  </Button>
                  </Col>
                  <Col span={12}>
                    <Button id="printBtn2" style={{width:102}}  type="primary" key="print2" onClick={()=>{
                    const el: any = document.getElementById('orderDetail');
                    // var btn: any = document.getElementById('printBtn1');
                    // btn.style.display ='none'
                    // btn = document.getElementById('printBtn2');
                    // btn.style.display ='none'
                    // btn = document.getElementById('printBtn3');
                    // btn.style.display ='none'
                    // btn = document.getElementById('printBtn4');
                    // btn.style.display ='none'
                      
                    setPrintFlag(true)
                    setTimeout(()=>{
                      var scrollTop = document.documentElement.scrollTop;
                      document.documentElement.scrollTop = 0;
                      const win: any = window.open('', 'printwindow');
                      html2canvas(el, {
                        useCORS: true,scale:2
                      }).then(canvas => {
                        // document.getElementById('printBtn1').style.display ='block'
                        // document.getElementById('printBtn2').style.display ='block'
                        // document.getElementById('printBtn3').style.display ='block'
                        // document.getElementById('printBtn4').style.display ='block'
                        setPrintFlag(false)
                        win.document.write(`<html><head><title>　</title></head></html>`)
                        win.document.body.appendChild(canvas);
                        win.print();
                        win.close();
                        document.documentElement.scrollTop = scrollTop;
                      });
                    },2000)
                 
                }} >打印当前页</Button>
                  </Col>
                  <Col span={12}>
                    <Button id="printBtn3" style={{width:102}}  type="primary" key="export3" onClick={()=>{
                        // genFile(0)
                    }}>

                      合同预览
                    </Button></Col>
                    <Col span={12}>
                    <Button id="printBtn4" style={{width:102}} type="primary" key="export4" onClick={()=>{
                        //  genFile(1)
                    }}>

                      合同下载
                    </Button>
                  </Col>
                </Row>
                
            </Col>
            <Col span={19} id='orderDetail'>
            <div style={{height:20}}></div>
            <Steps labelPlacement="vertical"  progressDot={(flag:any,data:any)=>{
                if(data.title=='待审核'){
                    if(data.status=='finish'){
                        return <Image preview={false} src={icon0s} width={40}></Image>
                    }
                    return <Image preview={false} src={icon0n} width={40}></Image>
                }else if(data.title=='待付款'){
                    if(data.status=='finish'){
                        return <Image preview={false} src={icon1s} width={40}></Image>
                    }
                    return <Image preview={false} src={icon1n} width={40}></Image>
                }else if(data.title=='待审核'){
                    if(data.status=='finish'){
                        return <Image preview={false} src={icon0s} width={40}></Image>
                    }
                    return <Image preview={false} src={icon0n} width={40}></Image>
                }else if(data.title=='待发货'){
                    if(data.status=='finish'){
                        return <Image preview={false} src={icon2s} width={40}></Image>
                    }
                    return <Image preview={false} src={icon2n} width={40}></Image>
                }else if(data.title=='待收货'){
                    if(data.status=='finish'){
                        return <Image preview={false} src={icon3s} width={40}></Image>
                    }
                    return <Image preview={false} src={icon3n} width={40}></Image>
                }else if(data.title=='已完成'){
                    if(data.status=='finish'){
                        return <Image preview={false} src={icon4s} width={40}></Image>
                    }
                    return <Image preview={false} src={icon4n} width={40}></Image>
                }else if(data.title=='未通过'||data.title=='已关闭'){
                  return <Image preview={false} src={icon5s} width={40}></Image>
              }
            }}>
                {getStep()}
            </Steps>
            <Divider />
            <div style={{paddingLeft:20}}>
                
                <Row>
                {
                  printFlag?
                  <>
                    <Col span={12}>
                    <Descriptions title="订单基本信息" column={1} size="small" labelStyle={{width:90,color:'#444444',fontWeight:700}}>
                      <Descriptions.Item  label="订单号">{order.orderNumber}</Descriptions.Item>
                      <Descriptions.Item  label="协议编号">{order.agreementNumber}</Descriptions.Item>
                      <Descriptions.Item  label="订单类型">{'普通订单'}</Descriptions.Item>
                      <Descriptions.Item  label="经销商名称">{order.buyer}</Descriptions.Item>
                      <Descriptions.Item label="订货日期">{order.orderTime}</Descriptions.Item>
                  
                      <Descriptions.Item  label="备注">{order.orderRemark?order.orderRemark+'':''}</Descriptions.Item>
                    </Descriptions>
                    </Col>
                    <Col span={12}>
                <Descriptions title="收货信息" column={1} size="small" labelStyle={{width:90,color:'#444444',fontWeight:700}} contentStyle={{paddingRight:20}}>
                    <Descriptions.Item label="收货人">{order?.postInfo?.contact}</Descriptions.Item>
                    <Descriptions.Item label="收货电话">{order?.postInfo?.phone}</Descriptions.Item>
                    <Descriptions.Item label="收货地址">{order?.postInfo?.province + order?.postInfo?.city + order?.postInfo?.address}</Descriptions.Item>
                </Descriptions>   </Col></>:<></>
                }

                    <Col span={24}>
                        <span style={{fontWeight:'bold',fontSize:14}}>订单详情</span>
                    </Col>
                    {/* <Col span={3} >
                        产品总数：<span style={{fontWeight:'bold',color:'#4091f7'}}>
                        {order?.orderProducts?.reduce(function (total:number, currentValue:any, currentIndex:number) {
                            return currentValue['quantity'] ? total + currentValue['quantity'] : total;
                          }, 0)}
                        </span>
                    </Col>
                    <Col span={6} >
                        总价：<span style={{fontWeight:'bold',color:'#fa9000'}}>￥{order.orderType=='4'?moneyFormat(order?.totalAmount):moneyFormat(order?.totalActualAmount)}</span>
                    </Col>
                    <Col span={6} >
                        实付金额(不含税)：<span style={{fontWeight:'bold',color:'#fa9000'}}>￥{moneyFormat(order?.totalActualAmountTaxExcluded)}</span>
                    </Col>
                    <Col span={6} >
                        实付金额(含税)：<span style={{fontWeight:'bold',color:'#fa9000'}}>￥{moneyFormat(order?.totalActualAmount)}</span>
                    </Col> */}
                </Row>
                <div style={{height:10}}></div>
                <ProTable
                    search={false} toolBarRender={false}
                    columns={columns}
                    pagination={false} 
                    rowKey="productId"
                    dataSource={proData}
                    size="small"
                    summary={pageData => {
                      return  <>
                      <Table.Summary.Row>
                  <Table.Summary.Cell index={1} colSpan={7}>合计订单件数：</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='left'>
                        {
                          proData?.reduce(function (total:number, currentValue:any, currentIndex:number) {
                            return currentValue['quantity'] ? total + currentValue['quantity'] : total;
                          }, 0)
                        }
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}/>
                  </Table.Summary.Row>
                  {order.orderType=='4'?
                    <>
                    <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={7}>
                      <span >总价（含税）：</span>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='left'>
                    ￥{moneyFormat(order.totalAmount)}

                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}/>
                  </Table.Summary.Row>
                  {/* <Table.Summary.Row>
                        <Table.Summary.Cell index={1} align='left' colSpan={8}>
                          <span style={{
                      }}>折扣金额：</span>
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} align='left'>
                          ￥-{moneyFormat(order.totalDiscount)}
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} colSpan={1}>
                        </Table.Summary.Cell>
                  </Table.Summary.Row> */}
                    </>:<></>
                  }
                  {order.orderType=='5'?
                    <>
                    <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={7}>
                      <span >总价（含税）：</span>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='left'>
                    ￥{moneyFormat(order.totalAmount)}

                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}/>
                  </Table.Summary.Row>
                  <Table.Summary.Row>
                        <Table.Summary.Cell index={1} align='left' colSpan={7}>
                          <span style={{
                      }}>折扣金额：</span>
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} align='left'>
                          ￥-{moneyFormat(order.totalDiscount)}
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={1} colSpan={1}>
                        </Table.Summary.Cell>
                  </Table.Summary.Row>
                    </>:<></>
                  }
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={7}>实付金额（不含税）：</Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='left'>
                    ￥{moneyFormat(order.totalActualAmountTaxExcluded)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}/>
                  </Table.Summary.Row>
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={1} colSpan={7}>
                      <span >实付金额（含税）：</span>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1} align='left'>
                    ￥{moneyFormat(order.totalActualAmount)}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} colSpan={1}/>
                  </Table.Summary.Row>
                </>;
                    }}
                />
                {
                  order.orderType==4?
                  <Row style={{
                    margin: '22px 0'
                  }}>
                    <Col span={24} >
                     <Descriptions title={<span style={{fontSize:14}}>折扣协议</span>}  bordered size="small" labelStyle={{width:120}} >
                        <Descriptions.Item label='协议编号'>{agreement?.agreeCode}
                        </Descriptions.Item>
                        <Descriptions.Item  label='年度'>{agreement?.agreeYear}
                        </Descriptions.Item>
                        <Descriptions.Item  label='截止日期'>{agreement?.deadline}
                        </Descriptions.Item>
                        <Descriptions.Item  label='折扣金额'>￥{moneyFormat(agreement?.agreeAmount)}
                        </Descriptions.Item>
                        <Descriptions.Item  label='折扣率'>{order.discountRate}
                        </Descriptions.Item>
                    </Descriptions>
                    </Col>  
                  </Row>
                  :<></>
                }
                 <Row hidden={!order?.orderOperationFlow?.operationOpinion} style={{
                  margin: '22px 0'
                }}>
                  <Col span={24} >
                    <Descriptions title={<span style={{fontSize:15}}>审核意见</span>}  bordered size="small" labelStyle={{width:120}} >
                      <Descriptions.Item span={1} label={order?.orderOperationFlow?.operationName}>
                        <div>{order?.orderOperationFlow?.operationOpinion}</div>
                      </Descriptions.Item>
                  </Descriptions>
                </Col>
              </Row>
            </div>
           </Col>
         </Row>
        </DrawerForm>
    );
});
export default OrderInfo;